<?php
    namespace App\Http\Controllers\Api\Web;

    use App\Http\Controllers\Controller;
    use App\Models\Commodity;
    use App\Models\CommodityList;
    use App\Models\ReBack;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;

    class CommodityController extends Controller{

        public function index(Request $request){
            $type = $request->type;
            $userId = $request->userId;
            $saleStatus = $request->saleStatus;
            $sql = Commodity::select("commodityId","caption","type","content","bgPicture","nowPrice","originalPrice");

            if ($type){
              $sql->where('type',$type);
            }
            if ($userId){
                $sql->where('userId',$userId);
            }
            if($saleStatus){
                $sql->where('saleStatus',$saleStatus);
            }
            $data = $sql->orderBy('commodityId','Desc')
                ->get()->toArray();
           

            return $this->apiResponse($data);
        }

        public function show($commodityId){
            $data = Commodity::find($commodityId);
            return $this->apiResponse($data);

        }

        public function store(Request $request)
        {
            $data = $request->all();
            
            $validator = Validator::make($data, [
                'commodityId'       => 'integer',
            ]);
            if($validator->fails()){
                return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
            }
            $commodityId = $data['commodityId'];
            unset($data['commodityId']);
            if($commodityId){
                $status = Commodity::where('commodityId',$commodityId)->update($data);
            }else{
                $data['type'] = '代售';
                $data['saleStatus'] = 2;

                $data['createTime'] = date('Y-m-d H:i:s');
                
                $status = Commodity::create($data);
                
            }
            if(!$status){
                return $this->apiResponse('', config('errorCode.UPDATE_FAILED'));
            }
            return $this->apiResponse('');

        }


    }